define(['plugins/echarts/echarts.min'], function (echarts) {

    var self,
        doc = document,
        app = win.app,
        layui = win.layui,
        element,
        table,
        table_where = {},
        cols = [],
        moduleName = '销售分析';
        var selfData = {
                list: [],
                names: [],
                percents: [],
                startDate: '',
                endDate: '',
                div1: true,
                div2: true,
                div3: true,
                div4: true,
            },
        typeData = {},
        showData={
            formData:[],
            chartData:{},
            headArray:[]
        },
            div1filed={field: 'GWCS014NAME',title: '人员',width: 150, fixed: 'left'},
            div2filed={field: 'GWCS024NAME',title: '省份',width: 80,search:'default'},
            div3filed={field: 'GWAM004NAME',title: '系列',width: 80,search:'default'},
            div4filed={field: 'GWAK054NAME',title: '渠道',width: 80}
    ;
        //取小数点后2位
        function around2(num){
            return Math.round(num*100)/100;
        }

    app.newModule({
        init: function () {
            self = this;
            cols=[[
                {field: 'ROW_ID',title: '序号',width: 60, fixed: 'left'}
                ,div1filed
                ,div2filed
                ,div3filed
                ,div4filed
                , {field: 'AMOUNT',title: '实际金额',width: 80}
                , {field: 'TARGETAMOUNT',title: '目标金额',width: 80}
                , {field: 'percent',title: '完成率(%)',width: 80}
            ]]
            let _searchsArr = app.cloneJSON(cols[0]);
            self._super({
                _tag: 'gwai740',
                _searchs: [{
                    id: 'gwai740', tableId: 'bfcgl',
                    datas:  _searchsArr.pushArray([
                        { field: 'GWAKL003', width: 160, title: '客户',sort: true,
                            search: 'default', searchOpts:{icon:true}}
                    ])
                }],
                _loadTplsFull: [{
                    dom: 'gwai740_edit', tpl: 'gwai740_edit'
                },{
                    dom: 'gwai740_shouli', tpl: 'gwai740_shouli'
                },{
                    dom: 'gwai740_paigong', tpl: 'gwai740_paigong'
                },{
                    dom: 'gwai740_huifang', tpl: 'gwai740_huifang'
                }, {
                    dom: 'common_open_window', tpl: 'common/_open_window'
                }]
            }, win);
        },

        initTable: function () {
            layui.use(['table'], function () {
                table = layui.table;
                table.render({
                    elem: app.getByid(doc, 'bfcgl'),
                    title: moduleName + '信息表',
                    id: 'bfcgl',
                    toolbar: '#table-toolbar',
                    defaultToolbar: [],
                    height: 'full',
                    cols: cols,
                    data:selfData.list,
                    loading: true,
                    page: true,
                    where: table_where
                });

            });

        },
        //初始化数据
        initData: function () {
            app.ajax({
                xurl: "/bb/xsfx/getInfo",
                xdata: {
                    startDate: selfData.startDate,
                    endDate: selfData.endDate
                },
                loading:true,
                cb: function (result) {

                    var data = result.data.data;
                    data.sortByKey('percent', true);
                    data.forEach(function (item, index) {
                        item.ROW_ID = index+1;
                        item['percent'] = (item.TARGETAMOUNT == 0 ? 100 : item.AMOUNT.div(item.TARGETAMOUNT) * 100);
                        item['percent'] = Math.round(item['percent']*100)/100;
                        item['AMOUNT'] = around2(item['AMOUNT']);
                        if (showData.headArray.length > 0) {
                            switch (showData.headArray[0]) {
                                case 0:
                                    item.showName = item.GWCS014NAME;
                                    // break;
                                case 1:
                                    item.showName = item.showName +'|'+item.GWCS024NAME;
                                    // break;
                                case 2:
                                    item.showName = item.showName +'|'+item.GWAM004NAME;
                                    // break;
                                case 3:
                                    item.showName = item.showName +'|'+item.GWAK054NAME;
                                    // break;
                            }
                        }else{
                            item.showName=item['GWCS014NAME']+'|'+item.GWCS024NAME+'|'+item.GWAM004NAME+'|'+item.GWAK054NAME
                        }
                        item.compareCode = item.showName;
                    })
                    selfData.list = data;
                    typeData['t1234']=data;
                    self.formChat(data);
                    self.initTable(data);
                }
            });
        },
        formChat: function (data) {

            var pieData = [];

            for (var i = 0, j = data.length; i < j; i++) {
                var item = data[i];
                pieData.push({
                    value: item.AMOUNT,
                    name: item.compareCode.substr(0,item.compareCode.length-1)
                    // name: item.showName
                });

            }
            var chartDiv = echarts.init(document.getElementById('divChart'));

            var option = {
                backgroundColor: '#fff',
                grid: {
                    top: 10,
                    left: 10,
                    right:10,
                    bottom: 30,
                    containLabel: true//这常用于『防止标签溢出』的场景
                },
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b} : {c} ({d}%)'
                },
                calculable: true,
                series: [{
                    name: '访问来源',
                    type: 'pie',
                    radius: '65%',
                    center: ['50%', '50%'],
                    data: pieData,
                    label: {
                        normal: {
                            formatter: function (a) {
                                return a.data.name + "(" + a.data.value + ")";
                            },
                            show: true,
                        },
                        emphasis: {
                            show: true,
                            textStyle: {
                                fontSize: '15',
                                fontWeight: 'bold'
                            }
                        }
                    },
                }]
            };

            chartDiv.setOption(option)
        },
        reloadTableCurr: function () {
            self._reloadTable({id: 'bfcgl', where: table_where});
        },
        _ready: function () {
            this._super({
            });

            var month = new Date().getCurrentMonth();
            selfData.startDate = month[0];//本月开始日期
            selfData.endDate = new Date().Format('yyyy-MM-dd');

            new Vue({
                el:document.getElementById('page'),
                data:{
                    dateRange:[selfData.startDate,selfData.endDate],
                    d:selfData
                },
                watch:{
                  'dateRange':function (res) {
                    var startDate=  new Date(res[0]);
                    var startmonth=startDate.getMonth()+1;
                    var startday=startDate.getDate();
                    var endDate=  new Date(res[1]);
                    var endmonth=endDate.getMonth()+1;
                    var endday=endDate.getDate();
                    selfData.startDate =startDate.getFullYear()+'-'+(startmonth<10?'0'+startmonth:startmonth)+'-'+(startday<10?'0'+startday:startday);
                    selfData.endDate = endDate.getFullYear()+'-'+(endmonth<10?'0'+endmonth:endmonth)+'-'+(endday<10?'0'+endday:endday);
                    self.initData();
                  },
                  'd.div1':function (res) {
                      var isok=false;

                      if (selfData.div1 || selfData.div2 || selfData.div3 || selfData.div4)
                          isok=true;

                      if (!isok){
                          this.$message.warning('至少选择一项!');
                          selfData.div1=true;
                          return;
                      }else
                          self.getShowData();
                   },
                  'd.div2':function (res) {
                      var isok=false;

                      if (selfData.div1 || selfData.div2 || selfData.div3 || selfData.div4)
                          isok=true;

                      if (!isok){
                          this.$message.warning('至少选择一项!');
                          selfData.div2=true;
                          return;
                      }else
                          self.getShowData();
                    },
                  'd.div3':function (res) {
                      var isok=false;

                      if (selfData.div1 || selfData.div2 || selfData.div3 || selfData.div4)
                          isok=true;

                      if (!isok){
                          this.$message.warning('至少选择一项!');
                          selfData.div3=true;
                          return;
                      }else
                          self.getShowData();
                    },
                  'd.div4':function (res) {
                      var isok=false;

                      if (selfData.div1 || selfData.div2 || selfData.div3 || selfData.div4)
                          isok=true;

                      if (!isok){
                          this.$message.warning('至少选择一项!');
                          selfData.div4=true;
                          return;
                      }else
                          self.getShowData();
                    },
                },
                methods:{

                }

            })
            self.initData();
        },
        getShowData:function(){
            console.log(selfData)
            var data = app.cloneJSON(typeData['t1234']);
            var showArray=[];
            data.forEach(function (d, index) {
                var show = {};//show的参数不固定
                //获取checked=true代表的取值
                var compareCode = '';
                var firstName = '';

                //div1filed={field: 'GWCS014NAME',title: '人员',width: 150, fixed: 'left'},
                //             div2filed={field: 'GWCS024NAME',title: '省份',width: 80,search:'default'},
                //             div3filed={field: 'GWAM004NAME',title: '系列',width: 80,search:'default'},
                //             div4filed={field: 'GWAK054NAME',title: '渠道',width: 80}

                if (selfData.div1) {
                    show.GWCS014NAME = d.GWCS014NAME;
                    compareCode +=  d.GWCS014NAME+'|';
                    div1filed={field: 'GWCS014NAME',title: '人员',width: 150, fixed: 'left'}
                }else{
                    div1filed={field: 'GWCS014NAME',title: '人员',width: 150, fixed: 'left',hide:true}
                }

                if (selfData.div2) {
                    show.GWCS024NAME = d.GWCS024NAME;
                    compareCode +=  d.GWCS024NAME+'|';
                    div2filed={field: 'GWCS024NAME',title: '省份',width: 80,search:'default'}
                }else{
                    div2filed={field: 'GWCS024NAME',title: '省份',width: 80,search:'default',hide:true}
                }

                if (selfData.div3) {
                    show.GWAM004NAME = d.GWAM004NAME;
                    compareCode +=  d.GWAM004NAME+'|';
                    div3filed={field: 'GWAM004NAME',title: '系列',width: 80,search:'default'}
                }else{
                    div3filed={field: 'GWAM004NAME',title: '系列',width: 80,search:'default',hide:true}
                }

                if (selfData.div4) {
                    show.GWAK054NAME = d.GWAK054NAME;
                    if(d.GWAK054NAME == undefined || d.GWAK054NAME =='' || d.GWAK054NAME.length < 1){
                    }else {
                        compareCode +=  d.GWAK054NAME+'|';
                    }

                    div4filed={field: 'GWAK054NAME',title: '渠道',width: 80}
                }else
                    div4filed={field: 'GWAK054NAME',title: '渠道',width: 80,hide:true}

                firstName = compareCode.split('|')[0]
                data.iFilter({
                    o: show,
                    cb: function (arr, i) {
                        if (i > 0){
                            show.TARGETAMOUNT=0;
                            show.AMOUNT=0;
                            arr.forEach(function (a, index) {
                                show.TARGETAMOUNT += a.TARGETAMOUNT;
                                show.AMOUNT += a.AMOUNT;
                            })
                            //计算：总实际除以总目标
                            var percent =(show.TARGETAMOUNT == 0 ? 100 : show.AMOUNT.div(show.TARGETAMOUNT) * 100);
                            show.percent = Math.round(percent*100)/100;
                            show.compareCode = compareCode;
                            show.showName=firstName;
                            show.AMOUNT = around2(show.AMOUNT);
                            var add=true;
                            for (var i = 0; i < showArray.length; i++) {
                                if (showArray[i].compareCode == show.compareCode){
                                    add=false;
                                    break;
                                }
                            }

                            if (add){
                                showArray.push(show);
                            }

                        }
                    }
                });
            });

            if (showArray.length > 0)
                showArray.forEach(function (arr, index) {
                    arr.ROW_ID = index+1;
                })
            selfData.list=showArray;
            self.formChat(selfData.list);

            cols=[[
                {field: 'ROW_ID',title: '序号',width: 60, fixed: 'left'}
                ,div1filed
                ,div2filed
                ,div3filed
                ,div4filed
                , {field: 'AMOUNT',title: '实际金额',width: 80}
                , {field: 'TARGETAMOUNT',title: '目标金额',width: 80}
                , {field: 'percent',title: '完成率(%)',width: 80}
            ]]

            self.initTable();
        },
        _lazy: function () {
            this._super();
            layui.use(['table'], function () {
                element = layui.element;
            });
        }
    });

});